package com.wits.qso.web.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import com.wits.platform.common.constants.ViewType;
import com.wits.platform.common.constants.WebConstants;
import com.wits.platform.common.utils.PageUtil;
import com.wits.platform.entity.User;
import com.wits.platform.service.UserService;
import com.wits.platform.web.controller.BaseController;
import com.wits.platform.web.mvc.PageParam;
import com.wits.qso.entity.Vm;
import com.wits.qso.entity.VmUser;
import com.wits.qso.service.VmService;
import com.wits.qso.service.VmUserService;

@Controller
@RequestMapping(value = "qso/vmuser")
public class VmUserController extends BaseController
{
	protected static final Logger logger = LoggerFactory.getLogger( VmUserController.class );
	@Autowired
	private VmService vmService = null;
	@Autowired
	private VmUserService vmUserService = null;
	@Autowired
	private UserService userService = null;
	
	@RequestMapping(value = "/toList")
	public String toList() {
		return "qso/vmuser/list";
	}

	@RequestMapping(value = "/list")
	@ResponseBody
	public String list(Model model, @ModelAttribute("page") PageParam page, HttpServletRequest request) {
		Map<String, Object> searchParams = Servlets.getParametersStartingWith( request, "search_" );

		Page<VmUser> listPage = vmUserService.findPage( VmUser.class, searchParams, page );

		model.addAttribute( "searchParams", Servlets.encodeParameterStringWithPrefix( searchParams, "search_" ) );

		return PageUtil.toAjaxPageResult( listPage.getTotalElements(), listPage.getContent() );
	}

	@RequestMapping(value = "/view/{viewType}")
	public String toView(Model model, @PathVariable String viewType, @RequestParam String id) {
		List<User> subtractUsers = ListUtils.subtract( userService.findAllTeacherAndStudent(), vmUserService.findExistedUser() );
		List<Vm> subtractVms = ListUtils.subtract( vmService.findAll(), vmUserService.findExistedVm() );
		
		if (ViewType.Add.getView().equals( viewType )) {
			model.addAttribute( WebConstants.COMMAND, new VmUser() );
		} else {
			VmUser vmUser = vmUserService.getOne( id );
			model.addAttribute( WebConstants.COMMAND, vmUser );
			subtractUsers.add( vmUser.getUser() );
			subtractVms.add( vmUser.getVm() );
		}
		
		model.addAttribute( "vmList", subtractVms );
		model.addAttribute( "userList", subtractUsers );
		model.addAttribute( "viewType", viewType );

		return "qso/vmuser/form";
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public Object save(Model model, @ModelAttribute("command") @Valid VmUser command, BindingResult result,
			@RequestParam(value = "viewType") String viewType, @RequestParam(value = "userId") String userId, @RequestParam(value = "vmid") String vmId) {
		 
		if (result.hasErrors()) {
			model.addAttribute( WebConstants.COMMAND, command );
			return toView( model, viewType, command.getId() );
		}
		
		if (ViewType.Add.getView().equals( viewType )) {
			command.setDateCre( new Date() );
			command.setUserCre( getCurrentUserId() );
		} else {
			command.setDateUpd( new Date() );
			command.setUserUpd( getCurrentUserId() );
		}

		try {
			command.setUser( userService.getOne( userId ) );
			command.setVm( vmService.getOne( vmId ) );
			
			vmUserService.save( command );
			return ajaxDoneSuccess( this.getText( "save.success" ) );
		} catch (Exception e) {
			return ajaxDoneError( this.getText( "save.failed" ), e );
		}
	}

	@RequestMapping(value = "/delete")
	@ResponseBody
	public Object delete(String ids) {
		try {
			vmUserService.deleteInBatch( Arrays.asList( StringUtils.split( ids, "," ) ) );
			return ajaxDoneSuccess( this.getText( "delete.success" ) );
		} catch (Exception e) {
			return ajaxDoneError( this.getText( "delete.failed" ), e );
		}
	}
}
